package com.hjrpc.babyyamall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.hjrpc.babyyamall.search.config.EsConfig;
import com.hjrpc.babyyamall.search.constant.EsConstant;
import com.hjrpc.babyyamall.search.constant.ProductSearchConstant;
import com.hjrpc.babyyamall.search.feign.ProductFeignService;
import com.hjrpc.babyyamall.search.service.ProductSearchService;
import com.hjrpc.babyyamall.search.vo.AttrResponseVo;
import com.hjrpc.babyyamall.search.vo.SearchParam;
import com.hjrpc.babyyamall.search.vo.SearchResult;
import com.hjrpc.common.dto.Sku4SearchTo;
import com.hjrpc.common.dto.es.SkuEsModel;
import com.hjrpc.common.exception.BizCodeEnum;
import com.hjrpc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSearchServiceImpl implements ProductSearchService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    ProductFeignService productFeignService;

    @Override
    public R up(List<Sku4SearchTo> sku4SearchTos) {
        //封装BulkRequest,批量处理请求
        BulkRequest bulkRequest = new BulkRequest();
        sku4SearchTos.stream().forEach(sku -> {
            IndexRequest indexRequest = new IndexRequest(ProductSearchConstant.PRODUCT_INDEX);
            indexRequest.source(JSON.toJSONString(sku), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        try {
            BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, EsConfig.COMMON_OPTIONS);
            if (bulkResponse.hasFailures()) {
                return R.error(BizCodeEnum.SEARCH_UNKNOWN_EXCEPTION);
            }
        } catch (IOException e) {
            log.error("出现异常{}", e);
            return R.error(BizCodeEnum.SEARCH_UNKNOWN_EXCEPTION);
        }
        return R.ok();
    }

    @Override
    public SearchResult searchProduct(SearchParam param) {
        // 封装查询请求
        SearchRequest searchRequest = buildSearchRequest(param);
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, EsConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            log.error("searchProduct出现异常{}", e);
        }
        // 封装返回请求
        SearchResult searchResult = buildSearchResult(searchResponse, param);
        return searchResult;
    }

    private SearchResult buildSearchResult(SearchResponse searchResponse, SearchParam searchParam) {
        SearchResult result = new SearchResult();
        SearchHits hits = searchResponse.getHits();

        //设置sku信息
        List<SkuEsModel> skuEsModelList = Arrays.stream(hits.getHits())
                .map(searchHit -> {
                    SkuEsModel skuEsModel = new Gson().fromJson(searchHit.getSourceAsString(), SkuEsModel.class);
                    if (StringUtils.isNotBlank(searchParam.getKeyword())) {
                        HighlightField skuTitle = searchHit.getHighlightFields().get("skuTitle");
                        skuEsModel.setSkuTitle(skuTitle.getFragments()[0].string());
                    }
                    return skuEsModel;
                }).collect(Collectors.toList());
        result.setProduct(skuEsModelList);

        // 所有涉及的属性
        ParsedNested parsedNested = searchResponse.getAggregations().get("attrsAgg");
        ParsedLongTerms parsedLongTerms = parsedNested.getAggregations().get("attrIdAgg");
        List<SearchResult.AttrVo> attrVos = parsedLongTerms.getBuckets().stream().map(bucket -> {
            String attrIdStr = bucket.getKeyAsString();
            ParsedStringTerms attrNameAggTerms = bucket.getAggregations().get("attrNameAgg");
            ParsedStringTerms attrValueAggTerms = bucket.getAggregations().get("attrValueAgg");
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo(Long.valueOf(attrIdStr),
                    attrNameAggTerms.getBuckets().get(0).getKeyAsString(),
                    attrValueAggTerms.getBuckets().stream()
                            .map(valueBucket -> valueBucket.getKeyAsString()).collect(Collectors.toList()));
            return attrVo;
        }).collect(Collectors.toList());
        result.setAttrs(attrVos);

        // 所有涉及的品牌
        ParsedLongTerms brandAggTerms = searchResponse.getAggregations().get("brandAgg");
        List<SearchResult.BrandVo> brandVos = brandAggTerms.getBuckets().stream().map(bucket -> {
            String brandId = bucket.getKeyAsString();
            ParsedStringTerms brandNameAggTerms = bucket.getAggregations().get("brandNameAgg");
            ParsedStringTerms brandImgAggTerms = bucket.getAggregations().get("brandImgAgg");
            return new SearchResult.BrandVo(Long.valueOf(brandId),
                    brandNameAggTerms.getBuckets().get(0).getKeyAsString(),
                    brandImgAggTerms.getBuckets().get(0).getKeyAsString());
        }).collect(Collectors.toList());
        result.setBrands(brandVos);

        // 所有涉及的分类
        ParsedLongTerms catalogAggTerms = searchResponse.getAggregations().get("catalogAgg");
        List<SearchResult.CatalogVo> catalogVos = catalogAggTerms.getBuckets().stream().map(bucket -> {
            ParsedStringTerms catalogNameAggTerms = bucket.getAggregations().get("catalogNameAgg");
            return new SearchResult.CatalogVo(Long.valueOf(bucket.getKeyAsString()),
                    catalogNameAggTerms.getBuckets().get(0).getKeyAsString());
        }).collect(Collectors.toList());
        result.setCatalogs(catalogVos);

        // 总条数
        long total = hits.getTotalHits().value;
        result.setTotal(total);

        // 总页数
        result.setTotalPages((int) (total % EsConstant.PRODUCT_PAGE_SIZE == 0 ? total / EsConstant.PRODUCT_PAGE_SIZE
                : total / EsConstant.PRODUCT_PAGE_SIZE + 1));

        // 每页条数
        result.setPageNum(searchParam.getPageNum());

        // 构建面包屑导航
        List<String> attrs = searchParam.getAttrs();
        if (attrs != null && attrs.size() > 0) {
            List<SearchResult.NavVo> navVos = attrs.stream().map(attr -> {
                String[] split = attr.split("_");
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                //6.1 设置属性值
                navVo.setNavValue(split[1]);
                //6.2 查询并设置属性名
                try {
                    R r = productFeignService.info(Long.parseLong(split[0]));
                    if (r.getCode() == 0) {
                        AttrResponseVo attrResponseVo = JSON.parseObject(JSON.toJSONString(r.get("attr")), new TypeReference<AttrResponseVo>() {
                        });
                        navVo.setNavName(attrResponseVo.getAttrName());
                    }
                } catch (Exception e) {
                    log.error("远程调用商品服务查询属性失败", e);
                }
                //6.3 设置面包屑跳转链接(当点击该链接时剔除点击属性)
                String queryString = searchParam.getQueryString();
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                    encode.replace("+", "%20");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = queryString.replace("&attrs=" + encode, "")
                        .replace("attrs=" + encode + "&", "").replace("attrs=" + encode, "");
                navVo.setLink("http://search.babyyamall.com/search.html" + (replace.isEmpty() ? "" : "?" + replace));
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVos);
        }


        log.info(new Gson().toJson(result));
        return result;
    }

    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //bool-query
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        //query-mush
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }

        //query-filter-catalogId
        if (searchParam.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }

        //query-filter-brandIds
        List<Long> brandIds = searchParam.getBrandId();
        if (!CollectionUtils.isEmpty(brandIds)) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", brandIds));
        }

        //query-filter-hasStock  1-true;0-false
        if (searchParam.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        }

        //query-filter-range-skuPrice
        if (StringUtils.isNotBlank(searchParam.getSkuPrice())) {
            String[] skuPrice = searchParam.getSkuPrice().split("-");
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            if (StringUtils.isNotBlank(skuPrice[0])) {
                rangeQueryBuilder.gte(skuPrice[0]);
            }
            if (skuPrice.length == 2 && StringUtils.isNotBlank(skuPrice[1])) {
                rangeQueryBuilder.lte(skuPrice[1]);
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }

        //query-filter-nested(attrs=1_3G:4G:5G&attrs=2_骁龙845&attrs=4_高清屏)
        List<String> attrs = searchParam.getAttrs();
        BoolQueryBuilder attrsNestedQueryBuilder = QueryBuilders.boolQuery();
        if (!CollectionUtils.isEmpty(attrs)) {
            attrs.forEach(x -> {
                String[] split = x.split("_");
                attrsNestedQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", split[0]));
                attrsNestedQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", split[1].split(":")));
            });
            NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", attrsNestedQueryBuilder, ScoreMode.None);
            boolQueryBuilder.filter(nestedQueryBuilder);
        }
        builder.query(boolQueryBuilder);

        // sort (sort=price/salecount/hotscore_desc/asc)
        String sort = searchParam.getSort();
        if (StringUtils.isNotBlank(sort)) {
            String[] sortArray = sort.split("_");
            builder.sort(sortArray[0], "asc".equalsIgnoreCase(sortArray[1]) ? SortOrder.ASC : SortOrder.DESC);
        }

        // size
        Integer pageNum = searchParam.getPageNum();
        builder.from((pageNum - 1) * EsConstant.PRODUCT_PAGE_SIZE);
        builder.size(EsConstant.PRODUCT_PAGE_SIZE);

        //highlight
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }

        //aggs - brandAgg
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg").field("brandId").size(10);
        brandAgg.subAggregation(AggregationBuilders.terms("brandNameAgg").field("brandName").size(10));
        brandAgg.subAggregation(AggregationBuilders.terms("brandImgAgg").field("brandImg").size(10));
        builder.aggregation(brandAgg);

        //aggs-catalogAgg
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalogAgg").field("catalogId").size(100);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalogNameAgg").field("catalogName").size(1));
        builder.aggregation(catalogAgg);

        //aggs-attrs
        NestedAggregationBuilder attrsAgg = AggregationBuilders.nested("attrsAgg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId").size(10);
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName").size(10));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue").size(10));
        attrsAgg.subAggregation(attrIdAgg);
        builder.aggregation(attrsAgg);

        log.debug("构建的DSL：{}", builder.toString());

        SearchRequest request = new SearchRequest(new String[]{ProductSearchConstant.PRODUCT_INDEX}, builder);
        return request;
    }
}
